<template>
  <view style="height: 100%">
    <scroll-view scroll-y class="viewport" v-if="goodsInfo.id">
      <!-- 基本信息 -->
      <view class="goods">
        <!-- 商品主图 -->
        <view class="preview">
          <swiper @change="changSwiper" circular>
            <swiper-item v-for="item in goodsInfo.mainPictures" :key="item">
              <image @tap="tapImages(item)" mode="aspectFill" :src="item" />
            </swiper-item>
          </swiper>
          <view class="indicator">
            <text class="current">{{ currentIndex + 1 }}</text>
            <text class="split">/</text>
            <text class="total">{{ goodsInfo.mainPictures.length }}</text>
          </view>
        </view>

        <!-- 商品简介 -->
        <view class="meta">
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ goodsInfo.price }}</text>
          </view>
          <view class="name ellipsis">{{ goodsInfo.name }}</view>
          <view class="desc">{{ goodsInfo.desc }}</view>
        </view>

        <!-- 操作面板 -->
        <view class="action">
          <!-- 点击的时候打开sku弹层，同时弹层内部既有立即购买，还有加入购物车，需要他的mode为1 -->
          <view class="item arrow" @tap="buttonClick({ index: -1 })">
            <text class="label">选择</text>
            <text class="text ellipsis">
              {{ selectArr || '请选择规格' }}
            </text>
          </view>
          <view class="item arrow" @tap="showPopup('address')">
            <text class="label">送至</text>
            <text class="text ellipsis">请选择收获地址</text>
          </view>
          <view class="item arrow" @tap="showPopup('service')">
            <text class="label">服务</text>
            <text class="text ellipsis">无忧退 快速退款 免费包邮</text>
          </view>
        </view>
      </view>

      <!-- 商品详情 -->
      <view class="detail panel">
        <view class="title">
          <text>详情</text>
        </view>
        <view class="content">
          <view class="properties">
            <!-- 属性详情 -->
            <view
              class="item"
              v-for="item in goodsInfo.details.properties"
              :key="item.value"
            >
              <text class="label">{{ item.name }}</text>
              <text class="value">{{ item.value }}</text>
            </view>
          </view>
          <!-- 图片详情 -->
          <image
            v-for="item in goodsInfo.details.pictures"
            :key="item"
            mode="widthFix"
            :src="item"
          ></image>
        </view>
      </view>

      <!-- 同类推荐 -->
      <view class="similar panel">
        <view class="title">
          <text>同类推荐</text>
        </view>
        <view class="content">
          <navigator
            v-for="item in goodsInfo.similarProducts"
            :key="item.id"
            class="goods"
            hover-class="none"
            :url="`/pages/goods/goods?id=${item.id}`"
          >
            <image class="image" mode="aspectFill" :src="item.picture"></image>
            <view class="name ellipsis">{{ item.name }}</view>
            <view class="price">
              <text class="symbol">¥</text>
              <text class="number">{{ item.price }}</text>
            </view>
          </navigator>
        </view>
      </view>
    </scroll-view>

    <!-- 用户操作 -->
    <view class="toolbar">
      <uni-goods-nav
        :options="options"
        :fill="true"
        :button-group="buttonGroup"
        @click="onClick"
        @buttonClick="buttonClick"
        style="width: 100%"
      />
    </view>
    <vk-data-goods-sku-popup
      ref="skuRef"
      :mode="mode"
      :localdata="localData"
      v-model="showSku"
      :amount-type="0"
      @close="closeSku"
      @add-cart="addCart"
      @buy-now="buyNow"
    />

    <uni-popup ref="popup" :safe-area="false">
      <AddressPanelVue @close="close" v-if="popName === 'address'" />
      <ServicePanelVue
        @close="close"
        v-if="popName === 'service'"
      ></ServicePanelVue>
    </uni-popup>
  </view>
</template>

<script>
// 父子组件嵌套，父组件使用了子组件内部的属性，渲染了页面
// befromCreate created, beforeMount 开始解析父组件的模板。
// 响应式更新的前提是，数据收集到了模板的依赖。
// 每一个数据处理成Object.defineProperty ,get set依赖
// 父组件提前使用了子组件的数据，导致这个数据没办法和父组件的模板建立关联。
import { addGoodsToCartApi } from '@/services/cart'
import { getGoodsByIdAPI } from '@/services/goods'
import { mapState } from 'vuex'
import AddressPanelVue from './components/AddressPanel.vue'
import ServicePanelVue from './components/ServicePanel.vue'
export default {
  components: {
    AddressPanelVue,
    ServicePanelVue,
  },
  computed: {
    ...mapState('system', ['safeAreaInsets']),
    // selecteAttr() {
    // 	// 当他的依赖项发生变化的时候，计算属性需要重新计算
    // 	// 返回子组件的属性
    // 	// 后续的时候，子组件的这个属性就算修改了，父组件的computed没有触发
    // 	return this.$refs.skuRef.selectArr.join(' ')
    // },
  },
  onLoad({ id }) {
    this.getGoodsById(id)
  },
  mounted() {},
  data() {
    return {
      goodsInfo: {},
      currentIndex: 0,
      popName: '',
      mode: 1,
      showSku: false,
      localData: {},
      buttonGroup: [
        {
          text: '加入购物车',
          backgroundColor: 'linear-gradient(90deg, #FFCD1E, #FF8A18)',
          color: '#fff',
        },
        {
          text: '立即购买',
          backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
          color: '#fff',
        },
      ],
      options: [
        {
          icon: 'chat',
          text: '客服',
        },
        {
          icon: 'shop',
          text: '店铺',
          info: 2,
          infoBackgroundColor: '#007aff',
          infoColor: '#f5f5f5',
        },
        {
          icon: 'cart',
          text: '购物车',
          info: 2,
        },
      ],
      selectArr: '',
    }
  },
  methods: {
    buyNow(ev) {
      console.log(ev)
      uni.navigateTo({
        url: `/pagesOrder/create/create?skuId=${ev._id}&count=${ev.buy_num}`,
      })
    },
    closeSku() {
      // console.log(23232)
      // console.log(this.$refs.skuRef.selectArr)
      // 子组件肯定初始化好了，然后再去获取数据，赋值到父组件的data里面，进行页面的渲染
      this.selectArr = this.$refs.skuRef.selectArr.join(' ').trim()
    },
    async addCart(e) {
      await addGoodsToCartApi({
        skuId: e._id,
        count: e.buy_num,
      })
      uni.showToast({
        title: '添加购物车成功',
      })
      // 关闭sku弹层
      this.showSku = false
    },
    // 点击了左侧的选项的时候触发
    onClick({ index }) {
      if (index === 2) {
        // 点击的事购物车，跳转购物车页面
        // 跳转非tabbar页面
        uni.navigateTo({
          url: '/pages/cart/index2',
        })
      }
    },
    buttonClick({ index }) {
      // 0 1   >> 2  3
      console.log(index) // 0 加入购物车  1立即购买
      this.mode = index + 2
      this.showSku = true
    },
    close() {
      this.$refs.popup.close()
    },
    showPopup(type) {
      // 点击要展示的弹层的类型记录在全局
      this.popName = type
      // 打开弹层
      this.$refs.popup.open('bottom')
    },
    async getGoodsById(id) {
      const { result } = await getGoodsByIdAPI(id)
      this.goodsInfo = result

      // 把后端返回的数据处理成sku组件所需要的数据
      this.localData = {
        _id: result.id, // 商品id
        name: result.name, // 商品名称
        goods_thumb: result.mainPictures[0], // 商品主图
        sku_list: result.skus.map((item) => ({
          _id: item.id, // sku >> id
          goods_id: result.id, // 商品id
          goods_name: result.name, // 商品名称
          image: item.picture, // sku图片
          price: item.price, // 当前sku价格
          sku_name_arr: item.specs.map((item) => item.valueName), // ['黑色', 'iphone11'] 属性值列表
          stock: item.inventory, // 库存量
        })),
        spec_list: result.specs.map((item) => ({
          // 规则列表
          list: item.values.map((item) => ({ name: item.name })), // 当前的规则所有的可选值
          name: item.name, // 规格的名称
        })),
      }
    },
    changSwiper(e) {
      this.currentIndex = e.detail.current
    },
    tapImages(url) {
      uni.previewImage({
        urls: this.goodsInfo.mainPictures,
        current: url,
      })
    },
  },
}
</script>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

swiper {
  height: 100%;

  image {
    height: 100%;
    width: 100%;
  }
}
uni-image {
  width: 100%;
  font-size: 0px;

  img {
    font-size: 0;
  }
}

.viewport {
  background-color: #f4f4f4;
  height: 90%;
}

.panel {
  margin-top: 20rpx;
  background-color: #fff;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 90rpx;
    line-height: 1;
    padding: 30rpx 60rpx 30rpx 6rpx;
    position: relative;
    text {
      padding-left: 10rpx;
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      border-left: 4rpx solid #27ba9b;
    }
    navigator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.arrow {
  &::after {
    position: absolute;
    top: 50%;
    right: 30rpx;
    content: '\e6c2';
    color: #ccc;
    font-family: 'erabbit' !important;
    font-size: 32rpx;
    transform: translateY(-50%);
  }
}

/* 商品信息 */
.goods {
  background-color: #fff;
  .preview {
    height: 750rpx;
    position: relative;
    .banner-swiper,
    .banner-swiper-item,
    .banner-swiper-image {
      width: 100%;
      height: 100%;
    }
    .indicator {
      height: 40rpx;
      padding: 0 24rpx;
      line-height: 40rpx;
      border-radius: 30rpx;
      color: #fff;
      font-family: Arial, Helvetica, sans-serif;
      background-color: rgba(0, 0, 0, 0.3);
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;
      .current {
        font-size: 26rpx;
      }
      .split {
        font-size: 24rpx;
        margin: 0 1rpx 0 2rpx;
      }
      .total {
        font-size: 24rpx;
      }
    }
  }
  .meta {
    position: relative;
    border-bottom: 1rpx solid #eaeaea;
    .price {
      height: 130rpx;
      padding: 25rpx 30rpx 0;
      color: #fff;
      font-size: 34rpx;
      box-sizing: border-box;
      background-color: #35c8a9;
    }
    .number {
      font-size: 56rpx;
    }
    .brand {
      width: 160rpx;
      height: 80rpx;
      overflow: hidden;
      position: absolute;
      top: 26rpx;
      right: 30rpx;
    }
    .name {
      max-height: 88rpx;
      line-height: 1.4;
      margin: 20rpx;
      font-size: 32rpx;
      color: #333;
    }
    .desc {
      line-height: 1;
      padding: 0 20rpx 30rpx;
      font-size: 24rpx;
      color: #cf4444;
    }
  }
  .action {
    padding-left: 20rpx;
    .item {
      height: 90rpx;
      padding-right: 60rpx;
      border-bottom: 1rpx solid #eaeaea;
      font-size: 26rpx;
      color: #333;
      position: relative;
      display: flex;
      align-items: center;
      &:last-child {
        border-bottom: 0 none;
      }
    }
    .label {
      width: 60rpx;
      color: #898b94;
      margin: 0 16rpx 0 10rpx;
    }
    .text {
      flex: 1;
      -webkit-line-clamp: 1;
    }
  }
}

/* 商品详情 */
.detail {
  padding-left: 20rpx;
  .content {
    margin-left: -20rpx;
    display: flex;
    flex-direction: column;

    image {
      width: 100%;
    }
  }
  .properties {
    padding: 0 20rpx;
    margin-bottom: 30rpx;
    .item {
      display: flex;
      line-height: 2;
      padding: 10rpx;
      font-size: 26rpx;
      color: #333;
      border-bottom: 1rpx dashed #ccc;
    }
    .label {
      width: 200rpx;
    }
    .value {
      flex: 1;
    }
  }
}

/* 同类推荐 */
.similar {
  padding-left: 20rpx;
  .content {
    padding: 0 20rpx 20rpx;
    margin-left: -20rpx;
    background-color: #f4f4f4;
    overflow: hidden;
    navigator {
      width: 305rpx;
      padding: 24rpx 20rpx 20rpx;
      margin: 20rpx 20rpx 0 0;
      border-radius: 10rpx;
      background-color: #fff;
      float: left;
    }
    .image {
      height: 260rpx;
      width: 100%;
    }
    .name {
      height: 80rpx;
      margin: 10rpx 0;
      font-size: 26rpx;
      color: #262626;
    }
    .price {
      line-height: 1;
      font-size: 20rpx;
      color: #cf4444;
    }
    .number {
      font-size: 26rpx;
      margin-left: 2rpx;
    }
  }
  navigator {
    &:nth-child(even) {
      margin-right: 0;
    }
  }
}

/* 底部工具栏 */
.toolbar {
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  .buttons {
    display: flex;
    & > view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }
    .addcart {
      background-color: #ffa868;
    }
    .buynow {
      background-color: #27ba9b;
      margin-left: 20rpx;
    }
  }
  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;
    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;
    }
    text {
      display: block;
      font-size: 34rpx;
    }
  }
}
</style>
